<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>原神优质图片仓库，广泛搜集，精挑细选</title>
    
    <!-- 外部资源：Bootstrap 5 CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    
    <!-- 自定义样式 -->
    <style>
        /********************
        * 导航栏样式
        ​********************/
        .nav-link {
            cursor: pointer; /* 显示手型指针 */
            transition: all 0.3s;
        }
        .nav-link.active {
            background-color: rgba(255,255,255,0.1); /* 激活状态背景 */
            transform: scale(1.05);
        }
        #officialDropdown:hover .dropdown-menu {
            display: block;
        }
        .navbar-brand {
            font-family: 'Microsoft YaHei', sans-serif;
            font-weight: bold;
        }
        /********************
        * 卡片样式
        ​********************/  
        #gallery {
            margin-top: 2rem;
        }      
        .image-card {
            cursor: pointer;
            transition: transform 0.2s;
            margin-bottom: 1.5rem;
        }
        .image-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
        }
        .card-img-top {
            cursor: pointer !important;
            height: 200px;
            object-fit: cover;
        }
        .card-title {
            height: 2.4em; /* 标题高度限制 */
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }
        /********************
        * 标签系统样式
        ​********************/
        .tag-btn.active {
            background-color: #0d6efd;
            color: white !important;
        }
        #tagsCollapse {
            transition: all 0.3s ease;
        }
        #selected-tags {
            color: #6c757d;
            padding-left: 0.5rem;
        }
        /********************
        * 模态框样式
        ​********************/
        #imageModal .modal-dialog {
            max-width: 90%;
        }
        #imageModal .modal-body img {
            max-height: 80vh;
            object-fit: contain;
        }
        #modalTags .badge {
            font-size: 0.9em;
            margin: 2px;
        }
        /********************
        * 动画效果
        ​********************/
        .like-btn.liked {
            animation: like 0.6s ease;
            color: #dc3545 !important;
            border-color: #dc3545 !important;
        }
        @keyframes like {
            0% { transform: scale(1); }
            30% { transform: scale(1.2); }
            60% { transform: scale(0.9); }
            100% { transform: scale(1); }
        }
    </style>
</head>
<body>
    <!-- 主页面结构 -->
    <!-- ================= 导航栏 ================= -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="#">原神优质图片仓库</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link active" href="#" data-type="">全部</a>
                    </li>
                    <li class="nav-item dropdown" id="officialDropdown">
                        <a class="nav-link dropdown-toggle" href="#" 
                        data-bs-toggle="dropdown" 
                        data-type="1"
                        aria-haspopup="true">官方图片</a>
                        <div class="dropdown-menu">
                            <a class="dropdown-item" href="#" data-type="1" data-category="1">版本主题</a>
                            <a class="dropdown-item" href="#" data-type="1" data-category="2">网页活动</a>
                            <a class="dropdown-item" href="#" data-type="1" data-category="3">生日贺图</a>
                            <a class="dropdown-item" href="#" data-type="1" data-category="4">周年/节日贺图</a>
                        </div>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-type="2">同人图</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-type="3">AI生成图</a>
                    </li>                
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-type="4">
                            AI工坊
                            <span class="badge bg-warning ms-1">开发中</span>
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

<!-- ================= 角色筛选区域 ================= -->
    <div class="container mt-3">
        <div class="row mb-2">
            <div class="col-12">
                <span class="fw-bold">角色筛选：</span>
                <span id="selected-tags">无</span>
                <button class="btn btn-sm btn-outline-secondary ms-2" id="clear-tags">清空</button>
            </div>
        </div>
        <div class="row">
            <div class="col-12">
                <div class="collapse" id="tagsCollapse">
                    <div class="d-flex flex-wrap gap-2 mb-2" id="tags-container">
                        <!-- 角色标签通过JS动态生成 -->
                    </div>
                </div>
                <a class="btn btn-link p-0" data-bs-toggle="collapse" href="#tagsCollapse">
                    展开/收起角色标签
                </a>
            </div>
        </div>
    </div>

    <!-- ================= 图片容器 ================= -->
    <div class="container" id="gallery">
        <div class="row" id="image-container">
            <!-- 图片卡片动态加载位置 -->
            <div class="col-12 text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
            </div>
        </div>
    </div>

    <!-- ================= 大图模态框 ================= -->
    <div class="modal fade" id="imageModal" tabindex="-1" aria-labelledby="imageModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="imageModalLabel"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-8">
                            <img src="" class="img-fluid rounded-3" id="modalImage" loading="lazy">
                        </div>
                        <div class="col-md-4">
                            <div class="d-flex gap-2 mb-3">
                                <button class="btn btn-danger like-btn" id="modalLikeBtn">
                                    <i class="bi bi-heart"></i>
                                    <span class="count">0</span>
                                </button>
                                <a href="#" class="btn btn-primary" id="modalDownloadBtn" download>
                                    <i class="bi bi-download"></i> 下载原图
                                </a>
                            </div>
                            <dl class="row">
                                <dt class="col-sm-4">分类类型</dt>
                                <dd class="col-sm-8"><span id="modalType"></span></dd>
                                
                                <dt class="col-sm-4">所属分类</dt>
                                <dd class="col-sm-8"><span id="modalCategory"></span></dd>
                                
                                <dt class="col-sm-4">喜欢人数</dt>
                                <dd class="col-sm-8"><span id="modalLikes"></span></dd>
                                
                                <dt class="col-sm-4">下载次数</dt>
                                <dd class="col-sm-8"><span id="modalDownloads"></span></dd>
                            </dl>
                            <div class="tags-container" id="modalTags"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ================= 页脚 ================= -->
    <footer class="bg-dark text-white py-4">
        <div class="container">
            <div class="row">
                <div class="col-md-4 mb-3">
                    <h5>关于我们</h5>
                    <p>原神优质图片仓库，广泛搜集，精挑细选</p>
                </div>
                <div class="col-md-4 mb-3">
                    <h5>快速链接</h5>
                    <ul class="list-unstyled">
                        <li><a href="#" class="text-white text-decoration-none">服务条款</a></li>
                        <li><a href="#" class="text-white text-decoration-none">隐私政策</a></li>
                    </ul>
                </div>
                <div class="col-md-4">
                    <h5>联系我们</h5>
                    <p>1341800950@qq.com<br>+86 177 5640 1148</p>
                </div>
            </div>
    
        </div>
    </footer>

    <!-- ================= 免责声明 ================= -->
    <section class="disclaimer bg-light py-3">
        <div class="container">
            <div class="row">
                <div class="col-12">
                    <p class="text-muted small mb-0">
                        免责声明：本网站所有图片均来源于网络公开资源，仅供学习交流使用，不构成任何商业目的。如有图片涉及版权问题，请及时联系管理员删除。使用者应自行判断内容的真实性和合法性，本网站不承担由此引起的任何法律责任。
                    </p>
                </div>
            </div>
        </div>
    </section>


    <!-- ================= 脚本资源：jQuery & Bootstrap JS ================= -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>


    <!-- 主业务逻辑 -->
    <script>
        // 全局状态
        const roles = [
            '群像', '阿贝多', '艾尔海森', '艾梅莉埃', '安柏', '八重神子', 
            '芭芭拉', '白术', '班尼特', '北斗', '重云', '达达利亚', 
            '迪奥娜', '迪卢克', '迪希雅', '多莉', '珐露珊', '菲米尼',
            '菲谢尔', '枫原万叶', '芙宁娜', '甘雨', '荒泷一斗',
            '胡桃', '基尼奇', '嘉明', '九条裟罗', '久岐忍', '卡齐娜',
            '卡维', '凯亚', '坎蒂丝', '科莱', '可莉', '克洛琳德',
            '刻晴', '莱欧斯利', '莱依拉', '蓝砚', '雷电将军', '雷泽',
            '林尼', '琳妮特', '流浪者', '丽莎', '鹿野院平藏', '旅行者',
            '罗莎莉亚', '玛拉妮', '玛薇卡', '梦见月瑞希', '米卡', '莫娜',
            '那维莱特', '纳西妲', '娜维娅', '凝光', '妮露', '诺艾尔',
            '欧洛伦', '派蒙', '七七', '绮良良', '恰斯卡', '千织',
            '琴', '赛诺', '赛索斯', '砂糖', '珊瑚宫心海', '申鹤',
            '神里绫华', '神里绫人', '提纳里', '托马', '温迪', '五郎',
            '希格雯', '茜特菈莉', '希诺宁', '夏洛蒂', '夏沃蕾', '闲云',
            '香菱', '宵宫', '魈', '辛焱', '行秋', '烟绯',
            '瑶瑶', '夜兰', '优菈', '云堇', '早柚', '钟离',
        ];
        let allImages = [];
        let selectedTags = [];
        let hoverTimer;
    
        // ================= 初始化入口 =================
        $(document).ready(() => {
            generateRoleTags();
            initializeData();
            bindGlobalEvents();
        });
    
        // ================= 核心功能 =================
        // 初始化数据
        function initializeData() {
            $.getJSON('/api/images')
                .done(data => {
                    allImages = data.map(img => ({
                        ...img,
                        tags: parseTags(img.tags),
                        id: img.id
                    }));
                    renderImages();
                })
                .fail(() => showError('图片加载失败，请稍后重试'));
        }
        // 渲染图片列表
        function renderImages(filterType = '', filterCategory = null) {
            const container = $('#image-container');
            showLoading(container);
    
            const filtered = filterImages(filterType, filterCategory);
            renderImageCards(filtered);
    
            updateEmptyState(filtered.length, filterType);
        }
        // 绑定全局事件
        function bindGlobalEvents() {
            // 导航筛选
            $(document).on('click', '.nav-link[data-type], .dropdown-item', handleNavClick);
            
            // 标签系统
            $(document).on('click', '.tag-btn', handleTagClick);
            $('#clear-tags').click(handleClearTags);
            
            // 图片交互
            $('#image-container').on('click', '.card-img-top', function(e) {
                const $card = $(e.currentTarget).closest('.image-card');
                const imageId = $card.find('.like-btn').data('id');
        
                if (!imageId) {
                console.warn('未找到图片ID', $card);
                return;
                }
                showImageModal(imageId);
            });

            // 点赞功能
            $(document).on('click', '.like-btn', function() {
                const $btn = $(this);
                const imageId = $btn.data('id');
                $btn.prop('disabled', true);
                
                $.post(`/api/like/${imageId}`)
                    .done(res => {
                        if (res.success) {
                            $(`.like-btn[data-id="${imageId}"] .count`).text(res.likes);
                            $('#modalLikes').text(`${res.likes} 人点赞`);
                        }
                    })
                    .always(() => {
                        $btn.prop('disabled', false)
                            .addClass('liked')
                            .delay(1000).queue(() => $btn.removeClass('liked').dequeue());
                    });
            });
        }
        
        // ================= 导航栏模块 =================
        // 处理导航点击
        function handleNavClick(e) {
            e.preventDefault();
            const $target = $(e.currentTarget);
            
            updateNavState($target);
            renderImages(
                $target.data('type') || '',
                $target.data('category') || null
            );
        }
        // 更新导航状态
        function updateNavState($target) {
            $('.nav-link, .dropdown-item').removeClass('active');
            $target.addClass('active');
            if ($target.hasClass('dropdown-item')) {
                $('#officialDropdown > .nav-link').addClass('active');
            }
        }
        // 下拉菜单悬停
        function initializeHover() {
            $('#officialDropdown').hover(
                () => hoverTimer = setTimeout(() => $('.dropdown-menu').show(), 300),
                () => {
                    clearTimeout(hoverTimer);
                    $('.dropdown-menu').hide();
                }
            );
        }
        // ================= 角色标签筛选模块 =================
        // 生成角色标签
        function generateRoleTags() {
            // 确保容器存在
            const $container = $('#tags-container');
            if ($container.length === 0) {
                console.error('找不到标签容器');
                return;
            }
    
            // 带数据验证的标签生成
            const validRoles = roles.filter(r => typeof r === 'string' && r.length > 0);
            const tagsHtml = validRoles.map(role => `
                <button class="btn btn-sm btn-outline-primary tag-btn mb-1" 
                        data-tag="${role.trim()}"
                        data-testid="tag-${role.trim()}">
                    ${role}
                </button>
            `).join('');
        
            $container.html(tagsHtml);
            console.log('生成标签数量:', validRoles.length);
        }

        // 处理标签点击
        function handleTagClick() {
            const $btn = $(this);
            const tag = $btn.data('tag');
            const index = selectedTags.indexOf(tag);
            if (index > -1) {
                selectedTags.splice(index, 1);
                $btn.removeClass('active');
            } else if (selectedTags.length < 5) {
                selectedTags.push(tag);
                $btn.addClass('active');
            }
            updateSelectedDisplay();
            triggerFilter();
        }

        // 更新已选标签展示
        function updateSelectedDisplay() {
            const display = selectedTags.slice(0, 3);
            let text = display.join(', ');
            if (selectedTags.length > 3) text += ` 等${selectedTags.length - 3}个`;
            $('#selected-tags').text(text || '无');
        }

        function handleClearTags() {
            selectedTags = [];
            $('.tag-btn').removeClass('active');
            updateSelectedDisplay();
            triggerFilter();
        }
        // ================= 卡片模块 =================
        // 卡片渲染
        function renderImageCards(images) {
            const html = images.map(img => `
                <div class="col-lg-3 col-md-4 col-sm-6">
                    <div class="card image-card shadow-sm h-100" data-image-id="${img.id}">
                        <img src="/static/images/${img.file_name}" 
                             class="card-img-top" 
                             alt="${img.title}"
                             loading="lazy">
                        <div class="card-body">
                            <h5 class="card-title">${img.title}</h5>
                            <div class="d-flex justify-content-between small">
                                <span class="text-muted">${getTypeName(img.type)}</span>
                                ${img.category ? `<span class="badge bg-info">${getCategoryName(img.category)}</span>` : ''}
                            </div>
                            ${img.tags.length ? `
                                <div class="mt-2">
                                    ${img.tags.map(t => `<span class="badge bg-secondary me-1">${t}</span>`).join('')}
                                </div>` : ''}
                        </div>
                        <div class="card-footer bg-transparent d-flex justify-content-between">
                            <button class="btn btn-sm btn-outline-danger like-btn" 
                                    data-id="${img.id}">
                                <i class="bi bi-heart"></i>
                                <span class="count">${img.likes || 0}</span>
                            </button>
                            <a href="/static/download/${img.id}" 
                               class="btn btn-sm btn-outline-primary download-btn"
                               download="${img.file_name}">
                                <i class="bi bi-download"></i>
                            </a>
                        </div>
                    </div>
                </div>
            `).join('');
            const $container = $('#image-container');
            $container.empty();
            $container.append(html);
            console.log(`渲染了${images.length}张卡片`, images);
        }
        // 处理图片点击
        function handleImageClick() {
            const $card = $(this).closest('.image-card');
            const imageId = $card.find('.like-btn').data('id');
            if (imageId) showImageModal(imageId);
        }

        // 处理喜欢点击
        function handleLikeClick() {
            const $btn = $(this);
            const imageId = $btn.data('id');
            
            $btn.prop('disabled', true);
            $.post(`/api/like/${imageId}`)
                .done(res => res.success && updateLikeUI(imageId, res.likes))
                .fail(() => showError('点赞失败'))
                .always(() => {
                    $btn.prop('disabled', false)
                        .addClass('liked')
                        .delay(1000).queue(() => $btn.removeClass('liked').dequeue());
                });
        }
    
        // ================= 模态框相关 =================
        // 显示模态框
        function showImageModal(imageId) {
            const modal = $('#imageModal');
            modal.modal('show');
            resetModalContent();
    
            $.getJSON(`/api/images/${imageId}`)
                .done(data => updateModalContent(data))
                .fail(() => {
                    modal.modal('hide');
                    showError('加载详情失败');
                });
        }
    
        function updateModalContent(data) {
            $('#modalImage').attr('src', `/static/images/${data.file_name}`); 
            $('#imageModalLabel').text(data.title);
            $('#modalType').text(getTypeName(data.type));
            $('#modalCategory').text(data.category ? getCategoryName(data.category) : '无');
            $('#modalLikes').text(`${data.likes} 人点赞`);
            $('#modalDownloads').text(data.downloads);
            $('#modalTags').html(data.tags.map(t => 
                `<span class="badge bg-secondary">${t}</span>`
            ).join('') || '暂无标签');
        }
    
        // ================= 工具函数 =================
        // 过滤触发
        function triggerFilter() {
            const activeType = $('.nav-link.active').data('type') || '';
            renderImages(activeType);
        }

        // 获取过滤图片数据
        function filterImages(type, category) {
            return allImages.filter(img =>
                (!type || img.type == type) &&
                (!category || img.category == category) &&
                (selectedTags.length === 0 || selectedTags.some(t => img.tags.includes(t)))
            );
        }
        // 解析图片标签格式
        function parseTags(tags) {
            try {
                return tags ? JSON.parse(tags) : [];
            } catch {
                return tags?.split(',') || [];
            }
        }
        // 点赞更新
        function updateLikeUI(imageId, likes) {
            $(`.like-btn[data-id="${imageId}"] .count`).text(likes);
            $('#modalLikes').text(`${likes} 人点赞`);
        }
        // ================= 辅助函数 =================
        function resetModalContent() {
            $('#modalImage').attr('src', '');
            $('#imageModalLabel').text('加载中...');
            $('#modalType, #modalCategory, #modalLikes, #modalDownloads').text('');
            $('#modalTags').html('');
        }
        function showLoading(container) {
            container.html(`
                <div class="col-12 text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
            `);
        }
        function updateEmptyState(count, filterType) {
            if (count === 0) {
                $('#image-container').html(`
                    <div class="col-12 text-center text-muted py-5">
                        ${filterType ? '该分类下暂无图片' : '暂无图片'}
                    </div>
                `);
            }
        }
        // ================= 常量映射 =================
        const TYPE_MAP = {1: '官方', 2: '同人', 3: 'AI生成'};
        const CATEGORY_MAP = {1: '版本主题', 2: '网页活动', 3: '生日贺图', 4: '周年/节日'};
    
        function getTypeName(type) {
            return TYPE_MAP[type] || '其他';
        }

        function getCategoryName(category) {
            return CATEGORY_MAP[category] || '';
        }
    </script>

    <script src="https://kit.fontawesome.com/your-kit-code.js"></script>
</body>
</html>
